<?php

namespace App\Service\System;

use App\Enums\OpenShop\Feishu\CacheEnum;
use App\Http\Middleware\OpenShop\MerchantAppAuth;
use App\Library\Rms\RmsShopApi;
use App\Models\System\SystemNoticeCompleteModel;
use App\Models\System\SystemNoticeImagesModel;
use App\Models\System\SystemNoticesModel;
use App\Service\BaseService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Facades\Cache;
use Kuafu\File\FileUtil;

class SystemNoticeService extends BaseService
{
    public static function list($pageNum, $pageSize)
    {
        $paginator = SystemNoticesModel::query()
            ->where('id', '>', SystemNoticesModel::QUESTION_NOTICE)
            ->orderByDesc('createdAt')
            ->with(['noticeImagesRel'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $ids = $paginator->pluck('id')->toArray();
        $completeArr = [];
        SystemNoticeCompleteModel::query()
            ->whereIn('systemNoticeId', $ids)
            ->chunk(1000, function ($completes) use (&$completeArr){
                foreach ($completes as $complete) {
                    $completeArr[] = [
                        'noticeId' => $complete->systemNoticeId,
                        'uid' => $complete->createdByUid,
                    ];
                }
            });
        $body = RmsUserService::getRmsUserInfoByUserIds(array_merge($paginator->pluck('createdByUid')->toArray()));
        $list = $paginator->map(function ($item) use ($body, $completeArr){
            $owner = '';
            foreach (($body['data'] ?? []) as $user) {
                if ($user['id'] == $item->createdByUid) {
                    $owner = $user['username'];
                }
            }
            $completeCount = 0;
            foreach ($completeArr as $value) {
                if ($value['noticeId'] == $item->id) {
                    ++$completeCount;
                }
            }
            if (Cache::has(CacheEnum::RMS_SHOP_OWNER_COUNT)) {
                $shopOwnerCount = Cache::get(CacheEnum::RMS_SHOP_OWNER_COUNT);
            } else {
                $shopOwnerCount = RmsUserService::getShopOwnerCount()['count'] ?? '-';
                if ($shopOwnerCount != '-') {
                    Cache::put(CacheEnum::RMS_SHOP_OWNER_COUNT, $shopOwnerCount, 3600);
                }
            }
            $detail = $completeCount . '/' . $shopOwnerCount;
            $coverImage = '';
            $detailImages = [];
            if ($item->noticeImagesRel != null) {
                foreach ($item->noticeImagesRel as $image) {
                    if ($image->type == SystemNoticeImagesModel::IMAGE_TYPE_COVER) {
                        $coverImage = FileUtil::domain() . '/' . $image->image;
                    }
                    if ($image->type == SystemNoticeImagesModel::IMAGE_TYPE_DETAIL) {
                        $detailImages[] = FileUtil::domain() . '/' . $image->image;
                    }
                }
            }

            return [
                'id'               => $item->id,
                'title'            => $item->title,
                'content'          => $item->content,
                'typeText'         => $item->typeText,
                'type'             => $item->type,
                'startTime'        => $item->startTime ? date('Y-m-d H:i:s', $item->startTime) : '',
                'endTime'          => $item->endTime ? date('Y-m-d H:i:s', $item->endTime) : '',
                'presenceAreaText' => $item->presenceAreaText,
                'additionalHide'   => $item->additionalHide,
                'presenceArea'     => $item->presenceArea,
                'status'           => $item->status,
                'joinText'         => $detail ?? '-',
                'owner'            => $owner,
                'coverImage'       => $coverImage,
                'detailImages'     => $detailImages,
                'createdAt'        => $item->createdAt->format('Y-m-d H:i:s'),
            ];
        });
        return [
            'list'      => $list,
            'count'     => $paginator->total(),
            'pageNum'   => $pageNum,
            'pageSize'  => $pageSize,
        ];
    }

    /**
     * 添加公告
     * @param $title
     * @param $type
     * @param $startTime
     * @param $endTime
     * @param $presenceArea
     * @param $content
     * @param $additionalHide
     * @param $additionalShow
     * @param $coverImg
     * @param $detailImages
     * @param $userInfo
     * @return void
     */
    public static function save($id, $title, $type, $startTime, $endTime, $presenceArea, $content, $additionalHide, $additionalShow, $coverImg, $detailImages, $userInfo)
    {
        if ($id) {
            $systemNoticeModel = SystemNoticesModel::find($id);
        } else {
            $systemNoticeModel = new SystemNoticesModel();
        }
        $systemNoticeModel->title          = $title;
        $systemNoticeModel->type           = $type;
        $systemNoticeModel->startTime      = $startTime;
        $systemNoticeModel->endTime        = $endTime;
        $systemNoticeModel->presenceArea   = $presenceArea;
        $systemNoticeModel->content        = $content;
        $systemNoticeModel->additionalHide = $additionalHide;
        $systemNoticeModel->additionalShow = $additionalShow;
        $systemNoticeModel->createdByUid   = $userInfo->id;
        $systemNoticeModel->updatedByUid   = $userInfo->id;
        $systemNoticeModel->save();
        if ($type == SystemNoticesModel::NOTICE_TYPE_TEXT) {
            return;
        }
        if ($id) {
            //修改
            SystemNoticeImagesModel::where('systemNoticeId', $id)
                ->update(['isDeleted' => 1]);
        }
        if ($type == SystemNoticesModel::NOTICE_TYPE_IMAGE) {
            $noticeImageModel = new SystemNoticeImagesModel();
            $data = [
                [
                    'systemNoticeId' => $systemNoticeModel->id,
                    'type' => SystemNoticeImagesModel::IMAGE_TYPE_COVER,
                    'image' => str_replace(FileUtil::domain() . '/', '', $coverImg),
                    'createdAt' => time(),
                    'updatedAt' => time(),
                    'createdByUid' => $userInfo->id,
                    'updatedByUid' => $userInfo->id,
                ]
            ];
            foreach ($detailImages as $detailImg) {
                $data[] = [
                    'systemNoticeId' => $systemNoticeModel->id,
                    'type' => SystemNoticeImagesModel::IMAGE_TYPE_DETAIL,
                    'image' => str_replace(FileUtil::domain() . '/', '', $detailImg),
                    'createdAt' => time(),
                    'updatedAt' => time(),
                    'createdByUid' => $userInfo->id,
                    'updatedByUid' => $userInfo->id,
                ];
            }
            $noticeImageModel->addAll($data);
        }
    }

    public static function detail($id)
    {
        $data = SystemNoticesModel::query()
            ->where('id', $id)
            ->with(['noticeImagesRel'])
            ->first();
        if ($data == null) {
            return [];
        }
        $detail = $data->toArray();
        $detail['startTimeFormat'] = date('Y-m-d H:i:s', $detail['startTime']);
        $detail['endTimeFormat'] = date('Y-m-d H:i:s', $detail['endTime']);
        if ($detail['type'] == SystemNoticesModel::NOTICE_TYPE_IMAGE && $detail['notice_images_rel'] != []) {
            foreach ($detail['notice_images_rel'] as $value) {
                if ($value['type'] == SystemNoticeImagesModel::IMAGE_TYPE_COVER) {
                    $detail['cover'] = FileUtil::domain() . '/' . $value['image'];
                }
                if ($value['type'] == SystemNoticeImagesModel::IMAGE_TYPE_DETAIL) {
                    $detail['detail'][] = FileUtil::domain() . '/' . $value['image'];
                }
            }
        }
        return $detail;
    }

    public static function read($noticeId, $shopId, $type)
    {
        $noticeCompleteModel = new SystemNoticeCompleteModel();
        $noticeCompleteModel->systemNoticeId = $noticeId;
        $noticeCompleteModel->shopId = $shopId;
        $noticeCompleteModel->type = $type;
        $noticeCompleteModel->createdByUid = MerchantAppAuth::$userId;
        $noticeCompleteModel->save();
    }

    public static function getNoticeByShopId(int $shopId)
    {
        $shopInfo = (new RmsShopApi)->getShopByIds([$shopId], ['status']);
        $status = -1;
        // code = 1 正常返回
        if (isset($shopInfo['code']) && $shopInfo['code'] == 1) {
            $status = $shopInfo['data']['shopList'][0]['status'] ?? -1;
        }
        //获取用户已读公告
        $completes = SystemNoticeCompleteModel::query()
            ->where('createdByUid', MerchantAppAuth::$userId)
            ->where('systemNoticeId', '>', SystemNoticesModel::QUESTION_NOTICE)
            ->pluck('systemNoticeId')
            ->toArray();
        $noticeModel = SystemNoticesModel::query()
            ->whereNotIn('id', $completes)
            ->where('startTime', '<=', time())
            ->where('endTime', '>=', time())
            ->with(['noticeImagesRel', 'noticeCompleteRel' => function($q) {
                $q->orderByDesc('id');
            }])
            ->get();
        if ($noticeModel == null) {
            return [];
        }
        $list = $noticeModel->toArray();
        foreach ($list as $k => $value) {
            if ($value['type'] == SystemNoticesModel::NOTICE_TYPE_QUESTION && $value['id'] == SystemNoticesModel::QUESTION_NOTICE) {
                if ($status != RmsShopApi::SHOP_STATUS_ON) {
                    continue;
                }
                $list[$k]['additionalHide'] = $value['additionalHide'] . '?' . 'openid=' . $shopId;
                foreach ($value['notice_complete_rel'] as $noticeCompleteRel) {
                    if ($noticeCompleteRel['createdByUid'] == MerchantAppAuth::$userId && ($noticeCompleteRel['completeTime'] >= strtotime('-30day')) && $value['id'] == $noticeCompleteRel['systemNoticeId']) {
                        unset($list[$k]);
                        continue 2;
                    }
                }
            }
            if ($value['type'] == SystemNoticesModel::NOTICE_TYPE_IMAGE && $value['notice_images_rel'] != []) {
                foreach ($value['notice_images_rel'] as $item) {
                    if ($item['type'] == SystemNoticeImagesModel::IMAGE_TYPE_COVER) {
                        $list[$k]['cover'] = FileUtil::domain() . '/' . $item['image'];
                    }
                    if ($item['type'] == SystemNoticeImagesModel::IMAGE_TYPE_DETAIL) {
                        $list[$k]['detail'][] = FileUtil::domain() . '/' . $item['image'];
                    }
                }
            }
        }
        return array_values($list);
    }

    public static function finish($id, $pageNum, $pageSize)
    {
        if (Cache::has(CacheEnum::RMS_SHOP_OWNER_COUNT)) {
            $shopOwnerCount = Cache::get(CacheEnum::RMS_SHOP_OWNER_COUNT);
        } else {
            $shopOwnerCount = RmsUserService::getShopOwnerCount()['count'] ?? '-';
            if ($shopOwnerCount != '-') {
                Cache::put(CacheEnum::RMS_SHOP_OWNER_COUNT, $shopOwnerCount, 3600);
            }
        }
        $paginator = SystemNoticeCompleteModel::query()
            ->where('systemNoticeId', $id)
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $body = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());
        $joinIn = [];
        $paginator->each(function ($item) use ($body, &$joinIn) {
            foreach ($body['data'] as $value) {
                if ($value['id'] == $item->createdByUid) {
                    $joinIn[] = [
                        'name'  => $value['username'],
                        'phone' => $value['mobile'],
                    ];
                }
            }
        });
        return [
            'list'              => $joinIn,
            'count'             => $paginator->total(),
            'shopOwnerCount'    => $shopOwnerCount,
            'pageNum'           => $pageNum,
            'pageSize'          => $pageSize,
        ];
    }
}
